const { parseRule } = require('./parser')
const cheerio = require('cheerio')
const _ = require('lodash')
const request = require('./request')

function parseBook (source, doc) {
  const $ = cheerio.load(doc)

  const bookMap = {
    infoInit: 'ruleBookInfoInit',
    name: 'ruleBookName',
    author: 'ruleBookAuthor',
    kind: 'ruleBookKind',
    lastChapter: 'ruleBookLastChapter',
    introduce: 'ruleIntroduce',
    coverUrl: 'ruleCoverUrl',
    chapterUrl: 'ruleChapterUrl',
    chapterUrlNext: ''
  }

  const item = {}
  Object.keys(bookMap).forEach(prop => {
    item[prop] = _.trim(parseRule(source[bookMap[prop]], $))
  })

  return item
}

async function downloadBook (source, url) {
  if (!_.startsWith(url, 'http')) {
    url = source.bookSourceUrl + url
  }
  return request.get(url)
}

module.exports = {
  parseBook,
  downloadBook
}
